using System;
using System.Collections.Generic;
using System.Text;
using System.CodeDom.Compiler;
using System.IO;

namespace SharpMud.Server.Systems.Scripting.Processing.Source
{
    public sealed class FileScriptSource : ScriptSourceBase
    {
        private System.IO.FileInfo _ScriptSourceFile;
        private string _CachedCodeContents;
        private System.IO.FileSystemWatcher _FileSystemWatcher;

        internal FileScriptSource(System.IO.FileInfo scriptSourceFile, IScriptCompileContext scriptCompileContext)
            :base(new Uri(scriptSourceFile.FullName),scriptCompileContext)
        {
            _ScriptSourceFile = scriptSourceFile;
            _FileSystemWatcher = new System.IO.FileSystemWatcher(scriptSourceFile.DirectoryName,scriptSourceFile.Name);
            _FileSystemWatcher.Changed += new System.IO.FileSystemEventHandler(OnFileChanged);
            _FileSystemWatcher.Created += new System.IO.FileSystemEventHandler(OnFileChanged);
            _FileSystemWatcher.Deleted += new System.IO.FileSystemEventHandler(OnFileChanged);

            _FileSystemWatcher.EnableRaisingEvents = true;
        }

        void OnFileChanged(object sender, System.IO.FileSystemEventArgs e)
        {
            if (!_ScriptSourceFile.Exists)
            {
                _CachedCodeContents = String.Empty;
            }
            else
            {
                using (TextReader tr = _ScriptSourceFile.OpenText())
                {
                    _CachedCodeContents = tr.ReadToEnd();
                }
            }
        }

        protected override CodeDomProvider GetPreferredCompiler()
        {
            return LanguageRecognition.GetLanguageOfFile(_ScriptSourceFile);
        }

        protected override string GetCodeContents()
        {
            return _CachedCodeContents;
        }

        protected override void _Dispose()
        {
            this._FileSystemWatcher.Dispose();
        }
    }

}
